import { queryUserList, deleteUser, addUser, updateUser } from '../services/api';

export default {
  namespace: 'userList',

  state: {
    userList: [],
  },

  effects: {
    * fetch(_, { call, put }) {
      const response = yield call(queryUserList);
      yield put({
        type: 'queryList',
        payload: Array.isArray(response) ? response : [],
      });
    },
    * deleteFetch({ payload }, { call, put }) {
      const response = yield call(deleteUser, payload);
      const queryList = yield call(queryUserList);
      console.log(response);
      yield put({
        type: 'deleteUser',
        payload: queryList,
      });
    },
    * addFetch({ payload }, { call, put }) {
      const response = yield call(addUser, payload);
      const queryList = yield call(queryUserList);
      console.log(response);
      yield put({
        type: 'addUser',
        payload: queryList,
      });
    },
    * updateFetch({ payload }, { call, put }) {
      const response = yield call(updateUser, payload);
      const queryList = yield call(queryUserList);
      console.log(response);
      yield put({
        type: 'updateUser',
        payload: queryList,
      });
    },
  },

  reducers: {
    queryList(state, action) {
      return {
        ...state,
        userList: action.payload,
      };
    },
    deleteUser(state, action) {
      return {
        ...state,
        userList: action.payload,
      };
    },
    addUser(state, action) {
      return {
        ...state,
        userList: action.payload,
      };
    },
    updateUser(state, action) {
      return {
        ...state,
        userList: action.payload,
      };
    },
  },
};
